import "./reset.css";
import { handleTree } from "@/utils/agentServerTree";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { type Ref, ref, computed, reactive, onMounted } from "vue";
import { getAccount } from "@/utils/auth";
import { PlusColumn } from "plus-pro-components";
import {
  callbackAgentConfig,
  delAgentConfig,
  getAgentConfList,
  getAgentServerTreeData2,
  publishAgentConfig,
  validateAgentConfig
} from "@/api/agent";
import { ElMessageBox } from "element-plus";

export function useAgentConf(tableRef: Ref, treeRef: Ref) {
  const dataList = ref([]);
  const curNodeName = ref("代理配置清单");
  const loading = ref(true);
  const roleInfo = getAccount().accountType;
  const curTenantId = getAccount().tenantId;

  const settingVisible = ref(false);
  const canAdd = ref(true);
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const agentConfContext = reactive<any>({
    pid: "",
    confVersion: "",
    confContext: ""
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 80]
  });
  const columns: PlusColumn[] = [
    {
      label: "版本号",
      width: 160,
      prop: "confVersion",
      valueType: "text"
    },
    {
      label: "配置内容",
      width: 160,
      prop: "confContext",
      valueType: "text"
    }
  ];

  const tableColumns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 60
    },
    {
      label: "配置块类型",
      prop: "confType",
      width: 120
    },
    {
      label: "配置版本",
      prop: "confVersion",
      width: 180,
      showOverflowTooltip: true
    },
    {
      label: "配置内容",
      prop: "confContext",
      width: 180,
      showOverflowTooltip: true,
      hide:true
    },
    {
      label: "变更时间",
      prop: "updateTime",
      width: 180
    },
    {
      label: "状态",
      prop: "confStatusDisplay"
    },
    {
      label: "操作",
      fixed: "right",
      width: 360,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function handleUpdate(row) {
    console.log(row);
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    if (curClickDId.value === "root") {
      curClickDId.value = "";
    }
    let section = "";

    let params = {};
    if (curClickType.value === "cloud") {
      params = {
        curPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        confType: "server",
        belongId: curClickDId.value
      };
      section = "server";
    } else if (curClickType.value === "server") {
      params = {
        curPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        confType: "location",
        belongId: curClickDId.value
      };
      section = "location";
    } else if (curClickType.value === "global") {
      params = {
        curPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        confType: "global",
        belongId: curClickDId.value
      };
      section = "global";
    } else {
      section = "";
      dataList.value = null;
      pagination.currentPage = 0;
      pagination.total = 0;
    }
    if (section != "") {
      getAgentConfList(params)
        .then(result => {
          dataList.value = result.data.list.map(item => {
            const timeValue = item["updateTime"] as any;
            return {
              ...item,
              updateTime: timeValue.split(".")[0].replace("T", " ")
            };
          });
          pagination.total = result.data.total;
          pagination.pageSize = result.data.pageSize;
          pagination.currentPage = result.data.currentPage;
        })
        .catch(err => {
          message(`加载配置内容清单异常：${err.message}`, {
            type: "error"
          });
        });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    treeRef.value.onTreeReset();
    onSearch();
  };
  const curClickDId = ref();
  const curClickType = ref();
  function onTreeSelect({ pid, selected, nodeType, nodeName }) {
    if (nodeType == "cloud") {
      curNodeName.value = "【服务云】" + nodeName + "-代理配置清单";
      canAdd.value = false;
    } else if (nodeType == "server") {
      curNodeName.value = "【应用】" + nodeName + "-代理配置清单";
      canAdd.value = false;
    } else if (nodeType == "global") {
      curNodeName.value = nodeName + "-代理配置清单";
      canAdd.value = false;
    } else {
      curNodeName.value = "代理配置清单";
      canAdd.value = true;
    }
    const vpid = selected ? pid : "";
    curClickDId.value = vpid;
    curClickType.value = nodeType;
    onSearch();
  }

  function openDialog(row?: any) {
    settingVisible.value = true;

    agentConfContext.confVersion = row.confVersion;
    agentConfContext.pid = row.pid;
    agentConfContext.confContext = row.confContext;
  }


  function validateConfig(confId: string) {
    ElMessageBox.confirm(`确认要验证代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        validateAgentConfig(confId)
          .then(result => {
            message(`代理配置验证通过`, {
              type: "success"
            });
          })
          .catch(err => {
            message(`代理配置验证失败:${err.message}`, {
              type: "error"
            });
            onSearch();
          })
          .finally(() => {
            onSearch();
          });
      })
      .catch(() => {});
  }

  function publishAgentConf(confId: string) {
    ElMessageBox.confirm(`确认要发布代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        publishAgentConfig(confId)
          .then(result => {
            message(`代理配置发布成功`, {
              type: "success"
            });
            onSearch();
          })
          .catch(err => {
            message(`代理配置发布失败:${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {});
  }

  function callBackAgentConf(confId: string) {
    ElMessageBox.confirm(`确认要收回代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        callbackAgentConfig(confId)
          .then(result => {
            message(`代理配置收回成功`, {
              type: "success"
            });
            onSearch();
          })
          .catch(err => {
            message(`代理配置收回失败:${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {});
  }

  function delAgentConf(confId: string) {
    ElMessageBox.confirm(`确认要删除代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        delAgentConfig(confId)
          .then(result => {
            message(`代理配置删除成功`, {
              type: "success"
            });
            onSearch();
          })
          .catch(err => {
            message(`代理配置删除失败:${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {});
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    // 应用树
    let tenantId = "";
    if (roleInfo != 1) {
      tenantId = curTenantId;
    }
    getAgentServerTreeData2(roleInfo, tenantId)
      .then(data => {
        higherDeptOptions.value = handleTree(data.data);
        treeData.value = handleTree(data.data);
      })
      .catch(err => {
        message(`获取应用清单异常：${err.message}`, {
          type: "error"
        });
      });
    treeLoading.value = false;
  });

  return {
    loading,
    tableColumns,
    curNodeName,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleSizeChange,
    handleCurrentChange,
    settingVisible,
    columns,
    agentConfContext,
    canAdd,
    validateConfig,
    publishAgentConf,
    callBackAgentConf,
    delAgentConf
  };
}
